package com.ksyun.campus.dataserver.controller;

import com.ksyun.campus.dataserver.domain.ReplicaData;
import com.ksyun.campus.dataserver.param.FileReadParam;
import com.ksyun.campus.dataserver.param.FileWriteParam;
import com.ksyun.campus.dataserver.services.DataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController("/")
@Slf4j
public class DataController {

    @Resource
    private DataService dataService;


    /**
     * 1、读取request content内容并保存在本地磁盘下的文件内
     * 2、同步调用其他ds服务的write，完成另外2副本的写入
     * 3、返回写成功的结果及三副本的位置
     * OSS对象存储 文件在 物理磁盘上 毫无规律
     * 入参: byte 文件、boolean flag true -> 主写 false -> 同步副本
     *
     * @return
     */
    @RequestMapping(value = "write", method = RequestMethod.POST)
    public ResponseEntity<List<ReplicaData>> writeFile(@RequestBody FileWriteParam fileWriteParam, @RequestParam MultipartFile data) {
        byte[] dataBytes;
        try {
            dataBytes = data.getBytes();
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        List<ReplicaData> rs = dataService.write(fileWriteParam.getPath(), dataBytes, fileWriteParam.getMainDataFlag());
        if (rs != null && rs.size() > 0) {
            return new ResponseEntity<>(rs, HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>(HttpStatus.SERVICE_UNAVAILABLE);
        }

    }

    /**
     * 在指定本地磁盘路径下，读取指定大小的内容后返回
     * 参数：id only
     *
     * @return
     */
    @RequestMapping(value = "read", method = RequestMethod.GET)
    public ResponseEntity<byte[]> readFile(@RequestParam FileReadParam fileReadParam) {
        byte[] read = dataService.read(fileReadParam.getId());
        //  return new ResponseEntity<>(read, HttpStatus.OK);
        // controller 返回 文件二进制数据的方式
        return read != null ? new ResponseEntity<>(read, HttpStatus.OK) : new ResponseEntity<>(read, HttpStatus.NOT_FOUND);
    }

    /**
     * 关闭退出进程
     */
    @RequestMapping("shutdown")
    public void shutdownServer() {
        System.exit(-1);
    }
}
